<template>
  <div class="header-search">
    <div class="search-input-wrapper">
      <el-popover
        popper-class="vs-popover-search"
        placement="bottom"
        width="780"
        v-model="searchIsShow"
        trigger="manual">
        <div style="position: relative;">
          <lk-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane v-for="(item,index) in tabList" :key="index" :label="item.label" :name="item.value">
              <div class="scroll-item">
                <component
                  :is="item.components"
                  ref="item.value"
                  :tableData="tableData"
                  :totalCount="totalCount"
                  @searchIsHide="hideSearchIs"
                ></component>
              </div>
              <div class="bottom-item">
                <div class="left-item">
                  <span>共查询到<span class="num-item">{{ totalCount }}</span>条结果</span>
                </div>
                <div class="right-item" @click="toMore">
                  <span>查看更多搜索结果</span>
                  <img src="../../../assets/image/icon/arrow-black.png" alt="">
                </div>
              </div>
            </el-tab-pane>
          </lk-tabs>
        </div>

        <el-input
          ref="searchInput"
          slot="reference"
          v-model="keywords"
          @focus="searchFocus"
          @input="querySearchAsync"
          @blur="searchBlur"
          @keyup.enter.native="toMore"
          placeholder="请输入关键词搜索"
          prefix-icon="el-icon-search"
          size="small"
          class="search-input"
          clearable></el-input>
      </el-popover>
    </div>
  </div>
</template>
<script>
import MixinTab from './MixinTab';
import MixinApi from './MixinApi';
import { Autocomplete } from 'element-ui';
import searchAll from './tabs/All.vue';
import searchProduct from './tabs/Product.vue';
import searchResearch from './tabs/Research.vue';
import searchBond from './tabs/Bond.vue';
import searchCompany from './tabs/Company.vue';
import searchDiscover from './tabs/Discover.vue';
import _ from 'lodash';
import { newverifyRoles } from '@/utils/verify';

export default {
  mixins: [MixinTab, MixinApi],
  provide () {
    return {
      hideSearchIs: this.hideSearchIs
    };
  },
  components: {
    [Autocomplete.name]: Autocomplete,
    searchAll,
    searchProduct,
    searchResearch,
    searchBond,
    searchCompany,
    searchDiscover
  },
  data () {
    return {
      activeName: 'all',
      loading: false,
      searchIsShow: false,
      isTabClick: false,
      keywords: '',
      searchData: [], // 搜索结果
      tabList: [
        { label: '全部', value: 'all', components: 'searchAll' },
        { label: '产品', value: 'product', components: 'searchProduct' },
        { label: '研究', value: 'research', components: 'searchResearch' },
        { label: '债券', value: 'bond', components: 'searchBond' },
        { label: '公司', value: 'company', components: 'searchCompany' },
        { label: '发现', value: 'discover', components: 'searchDiscover' }
      ]
    };
  },
  computed: {
    companyList () {
      return this.searchData.length > 0 ? _.uniqWith(this.searchData, function (arrVal, othVal) {
        return arrVal['detail'].sup_name === othVal['detail'].sup_name;
      }) : [];
    },
    // 总数据条数
    totalCount () {
      // 根据tab值activeName 筛选出 数组
      let tabData = [];
      switch (this.activeName) {
        case 'all':
          tabData.push(...Object.values(this.tableData).filter(item => item.typeName === '产品'));
          tabData.push(...Object.values(this.tableData).filter(item => item.typeName === '公司'));
          tabData.push(...Object.values(this.tableData).filter(item => item.typeName === '研究'));
          tabData.push(...Object.values(this.tableData).filter(item => item.typeName === '债券'));
          tabData.push(...Object.values(this.tableData).filter(item => item.typeName === '发现'));
          break;
        case 'product':
          tabData = Object.values(this.tableData).filter(item => item.typeName === '产品');
          break;
        case 'research':
          tabData = Object.values(this.tableData).filter(item => item.typeName === '研究');
          break;
        case 'company':
          tabData = Object.values(this.tableData).filter(item => item.typeName === '公司');
          break;
        case 'bond':
          tabData = Object.values(this.tableData).filter(item => item.typeName === '债券');
          break;
        case 'discover':
          tabData = Object.values(this.tableData).filter(item => item.typeName === '发现');
          break;
      }
      // 得到只含 totalCount的数组
      const countArr = tabData.filter(x => x.totalCount).map(x => x.totalCount || 0);
      if (countArr.length === 0) return 0;
      return countArr.reduce((a, c) => Number(a) + Number(c));
    }
  },
  mounted () {
    const result = newverifyRoles('xst');
    const judge = newverifyRoles('research');
    if (!result) {
      this.tabList = this.tabList.filter(item => item.label !== '产品' && item.label !== '公司');
    }
    if (!judge) {
      this.tabList = this.tabList.filter(item => item.label !== '研究');
    }
  },
  methods: {
   // 调用搜索接口
    getListData () {
      // 请求接口'
      this.getSearchData(this.keywords).then(res => {
        this.tableData = this.setTableData(this.highlightData(res, this.keywords, this.highlightKeys));
      });
    },
    setTableData (objData) {
      // eslint-disable-next-line no-new-object
      const newObjData = new Object();
      // 研究数据
      const researchData = {
        totalCount: 0,
        typeName: '研究',
        list: []
      };
      if (objData.BOND && objData.BOND.list.length > 0) {
        objData.BOND.list.forEach((item) => {
          if (item.srchtype === '22') {
            // eslint-disable-next-line no-unused-vars
            let dataObj = [];
            const key = 'full_name';
            const keywords = this.keywords;
            // eslint-disable-next-line no-const-assign
            dataObj = item.list.map(box => {
              if (box.detail.hasOwnProperty(key) && keywords) {
                box.detail[key + '_v'] = String(box.detail[key]).replaceAll(keywords, `<span class="${this.highlightCls}">${keywords}</span>`);
              }
            });
            objData.bonddata = {
              list: item.list,
              totalCount: item.rescount - 0,
              typeName: '债券'
            };
          }
          if (item.srchtype === '23') {
            // eslint-disable-next-line no-unused-vars
            let dataObj = [];
            const keys = ['issuer_name'];
            const keywords = this.keywords;
            dataObj = item.list.map(box => {
              keys.forEach(key => {
                if (box.detail.hasOwnProperty(key) && keywords) {
                  box.detail[key + '_v'] = String(box.detail[key]).replaceAll(keywords, `<span class="${this.highlightCls}">${keywords}</span>`);
                }
              });
            });
            objData.publisherdata = {
              list: item.list,
              totalCount: item.rescount - 0,
              typeName: '公司'
            };
          }
          if (item.srchtype === '24') {
            // eslint-disable-next-line no-unused-vars
            let dataObj = [];
            const keys = ['company_name'];
            const keywords = this.keywords;
            dataObj = item.list.map(box => {
              keys.forEach(key => {
                if (box.detail.hasOwnProperty(key) && keywords) {
                  box.detail[key + '_v'] = String(box.detail[key]).replaceAll(keywords, `<span class="${this.highlightCls}">${keywords}</span>`);
                }
              });
            });
            if (!newverifyRoles('xst')) {
              // 没有 基金管理人 权限
              objData.managerdata = {
                list: [],
                totalCount: 0,
                typeName: '公司'
              };
            } else {
              objData.managerdata = {
                list: item.list,
                totalCount: item.rescount - 0,
                typeName: '公司'
              };
            }
          }
          if (item.srchtype === '25') {
            // eslint-disable-next-line no-unused-vars
            let dataObj = [];
            const keys = ['first_tab'];
            const keywords = this.keywords;
            dataObj = item.list.map(box => {
              keys.forEach(key => {
                if (box.detail.hasOwnProperty(key) && keywords) {
                  box.detail[key + '_v'] = String(box.detail[key]).replaceAll(keywords, `<span class="${this.highlightCls}">${keywords}</span>`);
                }
              });
            });
            objData.discoverdata = {
              list: item.list,
              totalCount: item.rescount - 0,
              typeName: '发现'
            };
          }
        });
      } else {
        objData.bonddata = {
          list: [],
          totalCount: 0,
          typeName: '债券'
        };
        objData.publisherdata = {
          list: [],
          totalCount: 0,
          typeName: '公司'
        };
        objData.managerdata = {
          list: [],
          totalCount: 0,
          typeName: '公司'
        };
        objData.discoverdata = {
          list: [],
          totalCount: 0,
          typeName: '发现'
        };
      }
      for (const key in objData) {
        newObjData[key] = objData[key];
        // 是否有研究权限
        if (newverifyRoles('research')) {
          if (['REPORT', 'CHART', 'ACTIVITY', 'STOCK', 'AGGREGATION'].includes(key)) {
            researchData.totalCount += Number(objData[key].totalCount);
            objData[key].list.forEach(item => {
            item.title = item.title || item.stockName || item.chartName;
            const keywords = this.keywords;
            if (item.hasOwnProperty('title') && keywords) {
              item['title_v'] = String(item['title']).replaceAll(keywords, `<span class="${this.highlightCls}">${keywords}</span>`);
            }
          });
            researchData.list.push(objData[key]);
          }
        }
      }
      newObjData.researchData = researchData;
      return newObjData;
    },
    // 切换tab
    handleClick () {
      this.isTabClick = true;
      this.$refs.searchInput.focus();
      setTimeout(() => {
        this.isTabClick = false;
      }, 300);
    },
    // 搜索框blur
    searchBlur: _.debounce(function () {
      if (!this.isTabClick) {
        this.searchIsShow = false;
      }
    }, 200),
    hideSearchIs () {
      this.searchIsShow = false;
    },
    searchFocus (event) {
      if (event.target.value) { this.searchIsShow = true; }
    },
    // 搜索
    querySearchAsync: _.debounce(function (keywords) {
       if (keywords) {
        this.searchIsShow = true;
      } else {
        this.searchIsShow = false;
      }
      this.loading = true;
      this.searchData = [];

      if (!keywords) {
        this.searchData = [];
        this.loading = false;
      } else {
        this.getListData();
      }
    }, 300),
    // 跳转到搜索落地页
    toMore () {
      const routerParameter = this.activeName === 'all' ? '' : '/' + this.activeName;
      window.location.href = process.env.VUE_APP_SERVICE_SEARCH + routerParameter + '?keywords=' + this.keywords + '&activeName=' + this.activeName;
    }
  }
};
</script>

<style lang="scss" scoped>
.popper-search-input {
  li {
    padding: 5px;
    line-height: normal;

    .item-inner {
      .name {
        overflow: hidden;
        text-overflow: ellipsis;
        color: #333;
      }

      .type {
        font-size: 12px;
        color: #999;
      }
    }
  }
}
.lk-tabs{
  .el-tabs__nav-wrap::after{
    bottom: 1px;
  }
}
.el-tabs__item{
  height: 47px;
  line-height: 47px;
}
</style>

<style lang="scss" scoped>
.search-list{
  max-height: 216px;
  overflow-y: auto;
  .search-item {
    padding: 5px;
    line-height: normal;
    display: flex;
    align-items: center;
    cursor: pointer;
    user-select: none;
    &:hover{
      background-color: #F6F8FF;
    }
    .name {
      overflow: hidden;
      text-overflow: ellipsis;
      color: #333;
    }

    .type {
      border-radius: 4px;
      background: #EAF1FF;
      color:#2468F2;
      font-size: 12px;
      text-align: center;
      line-height: 18px;
      padding: 2px 8px;
      margin-right: 16px;
    }
  }
}
.header-search {
  display: flex;
  align-items: center;

  .search-input-wrapper {
    overflow: hidden;
    .search-input {
      width: 220px;
    }
  }
}
::v-deep .el-tabs__active-bar{
  width: 72px;
}
.scroll-item{
  height: 415px;
  margin-bottom: 10px;
  overflow-y: scroll;
  overflow-x: hidden;
}
::v-deep .scroll-item::-webkit-scrollbar {
  width: 12px; /*滚动条宽度*/
  height: 12px; /*滚动条高度*/
}
::v-deep .scroll-item::-webkit-scrollbar-thumb {
  border-radius: 6px; /*滚动条的圆角*/
  background: rgba(212, 216, 229, 0.6); /*滚动条的背景颜色*/
}
.bottom-item{
  display: flex;
  justify-content: space-between;
  align-items: center;
  .left-item{
    font-size: 14px;
    color: #7A7D96;
    .num-item{
      color: #2468F2;
      margin: 0 4px;
      font-weight: 600;
    }
  }
  .right-item{
    display: flex;
    align-items: center;
    cursor: pointer;
    span{
      font-weight: 400;
      font-size: 14px;
      color: #2468F2;
      margin-right: 6px;
    }
    img{
      width: 12px;
    }
  }
}
::v-deep .lk-tabs{
  .el-tabs__header{
    .el-tabs__nav-scroll{
      padding: 0;
      .el-tabs__item.is-top{
        font-size: 18px;
        font-weight: 600;
      }
      .el-tabs__item.is-active{
        color: #2468F2;
      }
      .el-tabs__active-bar{
        background: #2468F2;
      }
    }
  }
}
</style>
